layui.config({
    base: '../../layui/'
}).extend({
    treetable: 'treetable',
    dtree:'dtree'
}).use(['treeTable','layer','code','form','dtree', 'element'],function(){
    let $ = layui.$,
        form = layui.form,
        layer = layui.layer,
        treeTable = layui.treeTable,
        element = layui.element,
        dtree = layui.dtree
    ;

    // 直接下载后url: './data/table-tree.json',这个配置可能看不到数据，改为data:[],获取自己的实际链接返回json数组
    var	re = treeTable.render({
        elem: '#tree-table',
        url:"/server/list",
        icon_key: 'name',
        is_checkbox: true,
        hide_class: 'layui-hide',
        primary_key: 'id',
        top_value: -1,
        parent_key: 'parentId',
        treeColIndex: 0,
        icon: {
            open: 'layui-icon  dtree-icon-wenjianjiazhankai',
            close: 'layui-icon dtree-icon-weibiaoti5',
            left: 25,
        },
        end: function(e){
            form.render();
        },
        cols: [
            {
                key: 'name',
                title: '名称',
                width: '200px',
            },
            {
                key: 'ip',
                title: 'ip地址',
                width: '100px',
                align: 'center',
            },
            {
                key: 'username',
                title: '账户',
                width: '100px',
                align: 'center',
            },
            {
                key: 'password',
                title: '密码',
                width: '100px',
                align: 'center',
            },
            {
                key: 'port',
                title: '端口',
                width: '100px',
                align: 'center',
                template: function(item){
                    if (item.port===null){
                        return ""
                    }else {
                        return item.port
                    }
                }
            },
            {
                key: 'memoryFree',
                title: '剩余内存',
                width: '100px',
                align: 'center',
                template: function(item){
                    let v1 = item.memoryFree.substr(0,item.memoryFree.length - 1);
                    if(v1 < 2){
                        return '<span style="color:red;">'+item.memoryFree+'</span>';
                    }{
                        return item.memoryFree;
                    }
                }
            },
            {
                key: 'memoryTotal',
                title: '总内存',
                width: '100px',
                align: 'center',
            },
            {
                key: 'cpu',
                title: 'CPU利用率',
                width: '100px',
                align: 'center',
                template: function(item){
                    let v1 = item.cpu.substr(0,item.cpu.length - 1);
                    if(v1 > 90 ){
                        return '<span style="color:red;">'+item.cpu+'</span>';
                    }{
                        return item.cpu;
                    }
                }
            },
            {
                key: 'sort',
                title: '排序',
                width: '100px',
                align: 'center',
            },
            {
                key: 'vpn',
                title: '所需VPN',
                width: '100px',
                align: 'center',
            },
            {
                key: 'type',
                title: '类型',
                width: '100px',
                align: 'center',
                template: function(item){
                    if (item.type==0){
                        return '<span style="color:#ffc036;">目录</span>';
                    } else {
                        return '<span style="color:#1ba5ff;">虚拟机</span>';
                    }

                }
            },
            {
                title: '操作',
                width: '250px',
                align: 'center',
                template: function(item){
                    if (item.type==0){
                        return '<a lay-filter="add" class="layui-btn layui-btn-warm layui-btn-xs">添加</a>' +
                            '<a lay-filter="update" class="layui-btn layui-btn-blue layui-btn-xs">编辑</a>' +
                            '<a lay-filter="del" class="layui-btn layui-btn-danger layui-btn-xs">删除</a>'

                    } else {
                        return '<a lay-filter="ssh" class="layui-btn layui-btn-normal layui-btn-xs">终端</a>' +
                            '<a lay-filter="docker" class="layui-btn layui-btn-normal layui-btn-xs">docker</a>'+
                            '<a lay-filter="update" class="layui-btn layui-btn-blue layui-btn-xs">编辑</a>' +
                            '<a lay-filter="del" class="layui-btn layui-btn-danger layui-btn-xs">删除</a>';
                    }

                }
            }
        ]
    });
    treeTable.on('tree(flex)',function(data){
        console.log(JSON.stringify(data));
    })
    // 监听checkbox选择
    treeTable.on('tree(box)',function(data){
        if($(data.elem).parents('#tree-table1').length){
            var text = [];
            $(data.elem).parents('#tree-table1').find('.cbx.layui-form-checked').each(function(){
                $(this).parents('[data-pid]').length && text.push($(this).parents('td').next().find('span').text());
            })
            $(data.elem).parents('#tree-table1').prev().find('input').val(text.join(','));
        }
    })
    // 监听自定义 新增弹窗
    treeTable.on('tree(add)',function(data){
        add2(data.item)
    })
    // 监听自定义 编辑弹窗
    treeTable.on('tree(update)',function(data){
        update(data.item)
    })
    // 监听自定义 删除弹窗
    treeTable.on('tree(del)',function(data){
        del(data.item.id)
    })
    // 监听自定义 终端弹窗
    treeTable.on('tree(ssh)',function(data){
        ssh(data.item)
    })
    treeTable.on('tree(docker)',function(data){
        docker(data.item)
    })
    // 刷新重载树表（一般在异步处理数据后刷新显示）
    $('.refresh').click(function(){
        treeTable.render(re);
    })
    //刷新
    $('.refresh').click(function(){
        treeTable.render(re);
    })
    // 新增
    $('.add').click(function(){
        add();
    });
    // 删除
    $('.del').click(function(){
        const ids = treeTable.checked(re).join(',');
        if (ids == null || ids ==""){
            layer.msg("请先选择数据", {icon: 0,time: 2000}, function () {
                // location.reload(); // 页面刷新
            })
            return
        }
        del(treeTable.checked(re).join(','));
    });

    function del(ids) {

        layer.confirm("确认要删除吗，删除后不能恢复", { title: "删除确认" }, function (index) {
            $.ajax({
                type: "DELETE",//方法类型
                dataType: "json",//预期服务器返回的数据类型
                url: "/server/"+ids,//url
                contentType: "application/json;charset=utf-8",
                success: function (res) {
                    if (res.code == 0) {
                        layer.msg("删除成功", {icon: 1,time: 1000}, function () {
                            location.reload();
                        })
                    } else {
                        layer.msg(res.desc, {icon: 0}, function () {
                            // location.reload(); // 页面刷新
                            return false
                        })
                    }
                },
                error: function () {
                    alert("异常！");
                }
            });
        });




    }
    function add() {
        layer.open({
            type: 2,
            title: '新增服务器',
            area: ['500px', '600px'],
            fix: false, //
            closeBtn: true,
            shift: 2,
            shadeClose: true,
            content: ["server_add.html", 'no'],
            success: function (layero, index) {
                form.render();
            },
            yes: function () {
            }
        });
    }
    function add2(data) {
        layer.open({
            type: 2,
            title: '新增服务器',
            area: ['500px', '600px'],
            fix: false, //
            closeBtn: true,
            shift: 2,
            shadeClose: true,
            content: ["server_add_pid.html", 'no'],
            success: function (layero, index) {
                const body = layer.getChildFrame('body', index);//获取弹出层的dom元素
                // const iframeWin = layero.find('iframe')[0].contentWindow;
                body.find("#parentId").val(data.id);
                body.find("#parentName").val(data.name);
                form.render();
            },
            yes: function () {
            }
        });
    }

    function update(data) {
        layer.open({
            type: 2,
            title: '编辑服务器',
            area: ['500px', '600px'],
            fix: false, //
            closeBtn: true,
            shift: 2,
            shadeClose: true,
            content: ["server_update.html", 'no'],
            success: function (layero, index) {
                const body = layer.getChildFrame('body', index);//获取弹出层的dom元素
                const iframeWin = layero.find('iframe')[0].contentWindow;
                body.find("#id").val(data.id);
                body.find("#type").val(data.type);
                body.find("#ip").val(data.ip);
                body.find("#name").val(data.name);
                body.find("#parentId").val(data.parentId);
                body.find("#username").val(data.username);
                body.find("#password").val(data.password);
                body.find("#port").val(data.port);
                body.find("#vpn").val(data.vpn);
                body.find("#sort").val(data.sort);
                iframeWin.layui.form.render();
            },
            yes: function () {
            }
        });
    }
    function docker(data) {
        $.ajax({
            type: "get",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: "/admDocker/getByIp/"+data.ip,//url
            success: function (result) {
                if (result.code == 0) {
                    window.open(result.data.portainerUrl);
                };
            },
            error: function () {
                alert("异常！");
            }
        });
    }
    function ssh(data) {
        let params = {
            "ip": data.ip,
            "username": data.username,
            "password": data.password,
            "port": data.port
        };
        window["sshParams"] = params;
        const newWindow = window.open("../ssh/webssh.html");

        const loop = setInterval(function () {
            if (newWindow.closed) {
                clearInterval(loop);
            } else {
                newWindow.document.title = data.ip;
            }

        }, 1000);
    }
    // 全部关闭
    $('.close-all').click(function(){
        treeTable.closeAll(re);
    })
    $('.open-all').click(function(){
        treeTable.openAll(re);
    })
    // 随机更换小图标
    $('.change-icon').click(function(){
        var arr = [
            {
                open: 'layui-icon dtree-icon-jian',
                close: 'layui-icon dtree-icon-jia',
                left: 25,
            },{
            open: 'layui-icon  dtree-icon-wenjianjiazhankai',
                close: 'layui-icon dtree-icon-weibiaoti5',
                left: 25,
            },
        ];
        var round = Math.round(Math.random()*(arr.length - 1));
        re.icon = arr[round];
        treeTable.render(re);
    })
    $('#tree').on('click','[data-down]',function(){
        $(this).find('span').length && $(this).parents('.layui-unselect').find('input').val($(this).text());
    })
    $('.layui-select-title').click(function(){
        $(this).parent().hasClass('layui-form-selected') ? $(this).next().hide() : $(this).next().show(),$(this).parent().toggleClass('layui-form-selected');
    })
    $(document).on("click", function(i) {
        !$(i.target).parent().hasClass('layui-select-title') && !$(i.target).parents('table').length && !(!$(i.target).parents('table').length && $(i.target).hasClass('layui-icon')) && $(".layui-form-select").removeClass("layui-form-selected").find('.layui-anim').hide();
    })

    $('#btn-search').click(function () {
        var keyword = $('#edt-search').val();
        var searchCount = 0;
        $('#tree-table').find(' tbody tr td').each(function () {
            $(this).css('background-color', 'transparent');
            var text = $(this).text();
            if (keyword != '' && text.indexOf(keyword) >= 0) {
                $(this).css('background-color', 'rgba(250,230,160,0.5)');
                if (searchCount == 0) {
                    treeTable.openAll('#tree-table');
                    $('html,body').stop(true);
                    $('html,body').animate({scrollTop: $(this).offset().top - 150}, 500);
                }
                searchCount++;
            }
        });
        if (keyword == '') {
            layer.msg("请输入搜索内容", {icon: 5});
        } else if (searchCount == 0) {
            layer.msg("没有匹配结果", {icon: 5});
        }
    });
})